import {
  chemicalAlias
} from '../../dataSource'

import request from '../../api/factor'
Page({
  /**
   * 组件的初始数据
   */
  data: {
    list: [],
    id: '',
    name: '',
    correctionAmount: {
      name: 'expansionFactor',
      text: '修正量',
      elementType: 'correctionAmount',
      value: '',
      label: '膨胀因子'
    }
  },

  /**
   * 组件的方法列表
   */

  onConfirm(arg, name) {

    const result = Object.keys(arg).map(it => {
      return {
        ...arg[it],
        elementType: it
      }
    })
    this.data.id === undefined ? this.add(name, result) : this.update(name,result);
  },
  update(name, result){
    request.updateFactor({
      name,
      id: this.data.id,
      factorDatas: result
    }, () => {
      wx.showModal({
        title: "操作已完成",
        content: "返回上一页？",
        success(res) {
          if (res.confirm) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    })
  },
  add(name, result){
    request.addFactor({
      name,
      factorDatas: result
    }, () => {
      wx.showModal({
        title: "操作已完成",
        content: "返回上一页？",
        success(res) {
          if (res.confirm) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    })
  },
  onClose() {
    this.triggerEvent('onClose')
  },
  onSubmit(event) {

    const target = event.detail.value;

    // 检测是否全部填了
    const nill = Object.keys(target).some(item => {
      return target[item] === ""
    })
    if (nill) {
      wx.showToast({
        title: '存在项目未填',
        icon: 'error'
      })
      return false
    }
    let obj = {};
    for (let it of Object.keys(target)) {
      if (it === 'name') continue;
      const keys = it.split('.');
      if (obj[keys[0]] === undefined) {
        obj[keys[0]] = {
          [keys[1]]: target[it]
        }
      } else {
        obj[keys[0]][keys[1]] = target[it]
      }
    }

    
    
    this.onConfirm(obj, target.name);

  },
  setDataSource() {
    const list = Object.keys(chemicalAlias);
    const arr = [],
      dataSource = this.properties.dataSource;
    this.setData({
      correctionAmount: {
        name: 'expansionFactor',
        text: '修正量',
        elementType: 'correctionAmount',
        value: dataSource['correctionAmount']?.expansionFactor,
        label: '膨胀因子'
      }
    })
    for (let key of list) {
      if (key === 'name' || key === 'lossOnIgnition') {
        continue
      } else {
        arr.push({
          name: chemicalAlias[key],
          value: key,
          values: {
            expansionFactor: dataSource[key]?.expansionFactor || '',
            fluxFactor: dataSource[key]?.fluxFactor || '',
            tensionFactor: dataSource[key]?.tensionFactor || '',
          }
        })
      }
    }
    this.setData({
      list: arr
    })
  },
  /**
   * 设置空模板
   */
  setTem() {
    const list = Object.keys(chemicalAlias);
    const arr = [];
    this.setData({
      correctionAmount: {
        name: 'expansionFactor',
        text: '修正量',
        elementType: 'correctionAmount',
        value: '',
        label: '膨胀因子'
      }
    })

    for (let key of list) {
      if (key === 'name' || key === 'lossOnIgnition') {
        continue
      } else {
        arr.push({
          name: chemicalAlias[key],
          value: key,
          values: {
            expansionFactor: '',
            fluxFactor: '',
            tensionFactor: '',
          }
        })
      }
    }
    this.setData({
      list: arr
    })
  },
  /**
   * 
   * @param {*} source 源 Array
   * @param {*} key 
   * @param {*} target 
   */
  findItem(source, key, target) {
    const result = source.find(it => it['elementType'] === key);
    if (result) return result[target]
    return undefined
  },
  /**
   * 查询因子
   */
  getFactor() {
    request.factorManage(this.data.id, res => {
      const list = Object.keys(chemicalAlias);
      const arr = [],
        dataSource = res?.factorDatas || [];

      this.setData({
        correctionAmount: {
          name: 'expansionFactor',
          text: '修正量',
          elementType: 'correctionAmount',
          value: dataSource.find(it => it.elementType === 'correctionAmount')?.expansionFactor,
          label: '膨胀因子'
        }
      })
      for (let key of list) {
        if (key === 'name' || key === 'lossOnIgnition') {
          continue
        } else {
          arr.push({
            name: chemicalAlias[key],
            value: key,
            values: {
              expansionFactor: this.findItem(dataSource, key, 'expansionFactor'),
              fluxFactor: this.findItem(dataSource, key, 'fluxFactor'),
              tensionFactor: this.findItem(dataSource, key, 'tensionFactor'),
            }
          })
        }
      }
      this.setData({
        list: arr,
        name: res.name
      })
      this.triggerResult(arr);
    })
  },
  triggerResult(arr) {
    let obj = {};
    arr.map(it => {
      obj[it.value] = it.values
    })
    obj['correctionAmount'] = this.data.correctionAmount.expansionFactor;
    this.triggerEvent('onConfirm', obj);
  },

  onLoad(options) {
    // 在组件实例进入页面节点树时执行
    // this.setDataSource();
    // this.getFactor();
    this.setData({
      id: options.id
    })
    wx.setNavigationBarTitle({
      title: `${options.id?'编辑':'创建'}因子模板`
    })
    options.id === undefined ? this.setTem() : this.getFactor();
  },


})